package de.duester.vectordrawing.object;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import de.duester.vectordrawing.GraphicalObject;

/**
 * @author Maxim Duester
 */
public class Image extends GraphicalObject {
	private Bitmap bitmap;

	/**
	 * 
	 */
	public Image() {
	}

	/**
	 * @param p
	 * @param drawable
	 */
	public Image(PointF p, Drawable drawable) {
		this(p, drawableToBitmap(drawable));
	}

	/**
	 * @param p
	 * @param bitmap
	 */
	public Image(PointF p, Bitmap bitmap) {
		super(p);
		this.bitmap = bitmap;
		setColors(new int[] {});
	}

	private static Bitmap drawableToBitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable)
			return ((BitmapDrawable) drawable).getBitmap();

		int width = drawable.getIntrinsicWidth();
		width = width > 0 ? width : 1;
		int height = drawable.getIntrinsicHeight();
		height = height > 0 ? height : 1;

		Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);

		return bitmap;
	}

	/* (non-Javadoc)
	 * @see de.duester.vectordrawing.GraphicalObject#getNonRotatedImage()
	 */
	@Override
	protected Bitmap getNonRotatedImage() {
		return bitmap;
	}

	/* (non-Javadoc)
	 * @see de.duester.vectordrawing.GraphicalObject#copy()
	 */
	@Override
	public GraphicalObject copy() {
		Image im = (Image) super.copy();
		im.bitmap = bitmap.copy(Config.ARGB_8888, false);
		return im;
	}

	/* (non-Javadoc)
	 * @see de.duester.vectordrawing.GraphicalObject#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object o) {
		if (!super.equals(o))
			return false;
		Image im = (Image) o;
		return (bitmap.equals(im.bitmap));
	}
}
